<?php //Controller strony głównej

include_once "BaseModel.php";
include_once "Post.php";
include_once "ImageEditor.php";
include_once "PostDAO.php";
include_once "UserDAO.php";

/*class AddPostError {
	public $field, $info;

	function __construct($field, $info = null) {
		$this->field = $field;
		$this->info = $info;
	}
}*/

class EditModel extends BaseModel {
	
	public function getData($params) {
		$data->headerEntries[] = URI::cssEntry('createPost');
		$data->loggedUserName = Session::getLoggedUserName();
		$data->pageOwner = $params->pageOwner;
		if($params->action == 'edit') {
			$data->errors = $this->addPost($params);
			if($data->errors != null) {
				echo $data->errors->field.': '.$data->errors->info;
			}
			//if($data->errors == null)
			//	$data->headerEntries[] = '<meta HTTP-EQUIV="REFRESH" content="2; url='.URI::getUrl(null, Session::getLoggedUserName()).'">';
		} else {
			$data->post = PostDAO::getInstance()->getPost($params->begin);
			echo 'j'.$data->post->getId();
		}
		return $data;
	}
	
	private function editPost($params) {
		$post = new Post();
		$post->setType($params->postParams->type);
		$post->setShowTitle(isset($params->postParams->showTitle) ? true : false);
		if(!isset($params->postParams->title))
			return new AddPostError("title");
		$post->setTitle($params->postParams->title);
		$post->setIsAuthor(isset($params->postParams->own) ? true : false);
		$post->setSource($params->postParams->source);
		$tags = $this->splitTagsString($params->postParams->tags);
		$post->setTags($tags);
		switch($params->postParams->type) {
			case Post::TYPE_IMAGE:
				$res = $this->addImagePost($post, $params);
				if($res)
					return $res;
				break;
			case Post::TYPE_QUOTE:
			case Post::TYPE_ARTICLE:
				$this->addTextPost($post, $params);
				break;
			case Post::TYPE_CSS:
				break;
			case Post::TYPE_MOVIE:
				$res = $this->addMovie($post, $params);
				if($res)
					return $res;
				break;
		}
		$user = UserDAO::getInstance()->getUser(Session::getLoggedUserName());
		//PostDAO::getInstance()->addPost($post, $user->getId());
		PostDAO::getInstance()->addPostWithContent($post, $user->getId());
		return null;
	}
	
	private function addImagePost(&$post, $params) {
		if(!is_uploaded_file($params->files->file['tmp_name'])) {
			if(!isset($params->postParams->title))
				return new AddPostError("file");
		} else {
			$type = ImageEditor::getType($params->files->file['name']);
			if($type == ImageEditor::TYPE_UNKNOWN) {
				return new AddPostError("file", "niepoprawny typ pliku.");
			}
			if(ImageEditor::getWidth($params->files->file['tmp_name']) > Post::getMaxImageWidth()) {
				$imageMiniature = ImageEditor::resizeToWidth($params->files->file['tmp_name'], Post::getMaxImageWidth(), $type);
				$miniatureFileName = URI::getFreeFileName(URI::getImagesUploadDir(), ImageEditor::getExtension($type));
				ImageEditor::saveImage($imageMiniature, $type, URI::getImagesUploadDir().'/'.$miniatureFileName);
				$post->setContent(URI::getImagesUploadDir().'/'.$miniatureFileName);
			} else
				$miniatureFileName = null;
			$imageFileName = URI::getFreeFileName(URI::getImagesUploadDir(), ImageEditor::getExtension($type));
			move_uploaded_file($params->files->file['tmp_name'], URI::getImagesUploadDir().'/'.$imageFileName);
			if($miniatureFileName != null) {
				$post->setImage(URI::getImagesUploadDir().'/'.$imageFileName);
			} else {
				$post->setContent(URI::getImagesUploadDir().'/'.$imageFileName);
				$post->setImage(null);
			}
			$post->setDescription($params->postParams->content);
		}	
		return null;
	}
	
	private function addTextPost(&$post, $params) {
		$post->setContent($params->postParams->content);
	}
	
	private function addMovie(&$post, $params) {
		$url = $params->postParams->source;
		if(substr($url, 0, 7) == 'http://')
			$url = substr($url, 7);
		if(substr($url, 0, 8) == 'https://')
			$url = substr($url, 8);
		$url = explode('/', $url);
		if($url[0] != 'www.youtube.com')
			return AddPostError("source", "niepoprawny adres (aktualnie akceptowany tylko youtube).");
		$strParams = str_replace(array('?', '&'), array('&&&', '&&&'), $url[1]);
		$strParams = explode('&&&', $strParams);
		for($i = 0; $i < count($strParams); ++$i) {
			$p[$i] = explode('=', $strParams[$i]);
		}
		$vidId = null;
		foreach($p as $param) {
			if($param[0] == 'v') {
				$vidId = $param[1];
				break;
			}
		}
		if($vidId == null) {
			return new AddPostError("source", "niepoprawny adres.");
		}
		$content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.$vidId.'" frameborder="0" allowfullscreen></iframe>';
		$post->setContent($content);
		return null;
	}
	
	private function splitTagsString($string) {
		$string = str_replace(array(',', "\n", "\t", ';'), array(' ', ' ', ' ', ' '), $string);
		while (strpos($string,'  ') !== false) 
			$string = str_replace('  ',' ',$string);
		$string = trim($string);
		return explode(' ', $string);
	}
}

?>